//
//  SettingController.m
//  敢唆嘛!
//
//  Created by lanou on 15/11/23.
//  Copyright © 2015年 zms. All rights reserved.
//

#import "SettingController.h"
#import "imageviewAndLabel.h"
#import "Device.h"
#import "LoginController.h"
#import "HomePageController.h"
#import "Define.h"
#import "AmendUserViewController.h"
#import "ExitController.h"
#import "MessageCenterController.h"
#import "RecentlyReadController.h"
#import "Off-LineReadController.h"
#import "MessageCell.h"
#import "MessageModel.h"

@interface SettingController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic,retain)imageviewAndLabel *userView;
@property(nonatomic, strong)UITableView *messageTableView;
@property(nonatomic, strong)NSMutableArray *messageArray;
@end

static NSString *cellIdentifier = @"message";
@implementation SettingController

// 查询bmob数据库表内所有内容 最多1000 默认100
- (void)findAllHomeData
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"Message"];
    [bquery orderByDescending:@"createdAt"];
    bquery.limit = 1000;
    //查找Recommend表的数据
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error)
        {
            // 判断网络连接
            if (![[NetWorkState shareInstance] reachability])
            {
                [self alertActionWithTitle:@"提示" message:@"网络不通" other:@"确定"];
            };
            NSLog(@"error:%@",error);
        }
        else
        {
            // 数据请求成功后才初始化数组 否则会造成下拉刷新崩溃
            self.messageArray = [NSMutableArray array];
            for (BmobObject *obj in array)
            {
                MessageModel *model = [[MessageModel alloc] initWithObj:obj];
                [self.messageArray addObject:model];
            }
            // 需要在主线程里面进行刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.messageTableView reloadData];
            });
        }
    }];
}

// 返回按钮触发
- (void)backBtnAction:(UIButton *)backBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationItem.title = @"用户中心";
    
    // 创建左上角返回按钮
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, KSWidth / 18, KSWidth / 18);
    [backBtn setImage:[UIImage imageNamed:@"iconfont-unie61e"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBackBtn = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftBackBtn;
    
    //设置用户界面的宽
    float width = KSWidth/4*3;
    
    UIView *colorView = [[UIView alloc] initWithFrame:CGRectMake(0, KSWidth / 15, width / 1.5, KSWidth / 10)];
    colorView.backgroundColor = [UIColor colorWithRed:188 / 255.0 green:49 / 255.0 blue:49 / 255.0 alpha:1.0];
    [self.view addSubview:colorView];
    
    //创建用户
    self.userView  = [[imageviewAndLabel alloc]initWithFrame:CGRectMake(0, 18, width, KSWidth/7)];

    //给每个小的视图添加手势
    UITapGestureRecognizer *userTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    
    [_userView addGestureRecognizer:userTap];
    
    [self.view addSubview:_userView];
    
    //确定上次是否已经登陆过
    BmobUser *bUer = [BmobUser getCurrentUser];
    if (bUer) {
        
        //用户头像设置
        BmobObject *object = [BmobObject objectWithoutDatatWithClassName:@"_User" objectId:bUer.objectId];
        BmobFile *file = [object objectForKey:@"userHeader"];
        
        if (file == nil) {
            _userView.imageView.image = [UIImage imageNamed:@"user.png"];
        }
        else{
            [_userView.imageView sd_setImageWithURL:[NSURL URLWithString:file.url]];
        }
        
        _userView.label.text = bUer.username;
        
    }
    else{
        _userView.label.text = @"游客";
        
        //用户头像设置
        _userView.imageView.image = [UIImage imageNamed:@"user.png"];

    }
    
    self.messageTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, KSHeight/5+KSWidth/8, width / 1.5, KSWidth/8) style:UITableViewStylePlain];
    self.messageTableView.scrollEnabled = NO;
    self.messageTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.messageTableView.backgroundColor = [UIColor colorWithRed:25 / 255.0 green:25 / 255.0 blue:36 / 255.0 alpha:1.0];
    self.messageTableView.delegate = self;
    self.messageTableView.dataSource = self;
    [self.messageTableView registerClass:[MessageCell class] forCellReuseIdentifier:cellIdentifier];
    [self.view addSubview:_messageTableView];
    
    [self findAllHomeData];
    
    //创建 我的主页 消息中心 近期阅读  离线阅读 四个视图
        
    imageviewAndLabel *view = [[imageviewAndLabel alloc]initWithFrame:CGRectMake(0, KSHeight/5+KSWidth/8*0, width, KSWidth/8)];
    
    //赋值数据
    view.label.text = @"我的主页";
    
    //赋值图片
    view.imageView.image = [UIImage imageNamed:@"article.png"];
    
    //添加一个轻拍手势
    UIGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [view addGestureRecognizer:tap];
    
    //将创建的视图添加到控制器的视图上
    [self.view addSubview:view];

    
    //设置 设置按钮和夜间模式按钮的宽度
    float setWidth = width/3;
    
    //设置按钮视图 和日夜间模式
    UIView *setView = [[UIView alloc]initWithFrame:CGRectMake(setWidth / 2, KSHeight- KSHeight/4, setWidth, width/8)];
    
    UIImageView *setImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, setWidth/3, setWidth/3)];
    
    setImageView.center = CGPointMake(setView.frame.size.width/2, 0);
    
    //添加图片
    setImageView.image = [UIImage imageNamed:@"set.png"];
    
    [setView addSubview:setImageView];
    
    //添加label
    UILabel *setLable = [[UILabel alloc]initWithFrame:CGRectMake(0, setImageView.frame.size.height+30, setWidth, setView.frame.size.height-setWidth)];
    
    setLable.text = @"设置";
    
    setLable.textAlignment = NSTextAlignmentCenter;
    
    setLable.textColor = [UIColor whiteColor];
    
    [setView addSubview:setLable];
    
    //添加轻拍手势
    UIGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    
    [setView addGestureRecognizer:tap2];
    
    //将按钮添加到控制器视图上
    [self.view addSubview:setView];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:25 / 255.0 green:25 / 255.0 blue:36 / 255.0 alpha:1.0];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //添加一个轻拍手势
    UIGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [cell.messageView addGestureRecognizer:tap];
    // 获取当前登录的用户
    BmobUser *bmobUser = [BmobUser getCurrentUser];
    if (bmobUser)
    {
        if (self.messageArray.count != 0)
        {
            BOOL isMessage = [[NSUserDefaults standardUserDefaults] boolForKey:@"message"];
            if (isMessage)
            {
                cell.messageRed.hidden = YES;
            }
            else
            {
                cell.messageRed.hidden = NO;
            }
        }
        else
        {
            cell.messageRed.hidden = YES;
        }
    }
    else
    {
        cell.messageRed.hidden = YES;
    }

    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

//提示页面
- (UIAlertController *)alertActionWithTitle:(NSString *)title message:(NSString *)message other:(NSString *)other
{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:other style:UIAlertActionStyleDefault handler:nil];
    [alertVc addAction:otherAction];
    [self presentViewController:alertVc animated:YES completion:nil];
    return alertVc;
}

#pragma mark --视图添加的轻拍手势 --
-(void)tapAction:(UITapGestureRecognizer *)tap{
    
    //判断是否有网络 如果没有网络
    if (![[NetWorkState shareInstance]reachability]) {
        
        [self alertActionWithTitle:@"提示" message:@"网络无连接" other:@"确定"];
    
        return;
    }
    
    //判断是那个视图添加的轻拍手势 并取出视图的label
    UILabel *tapLabel = tap.view.subviews[1];
    
    //判断是否登陆
    //确定上次是否已经登陆过
    BmobUser *bUer = [BmobUser getCurrentUser];
    if (bUer) {
        
        //是用户界面 或者是用户的主页 的轻拍手势
        if ([tapLabel.text isEqualToString:@"我的主页"]) {
            
//            已经登陆了 进入我的主页界面
            HomePageController *homePageVC = [[HomePageController alloc]init];
            
            [self.navigationController pushViewController:homePageVC animated:YES];
            
        }
        
        //点击用户 进入用户详情
        else if ([tapLabel.text isEqualToString:self.userView.label.text]){
            
            AmendUserViewController *amendVC = [[AmendUserViewController alloc]init];
            
            //将用户的头像传到用户详情界面
            amendVC.userHerder = self.userView.imageView;
            
            [self.navigationController pushViewController:amendVC animated:YES];
            
            //当登陆界面 成功后 程序才会执行这个block的代码快 就是进行回调
            //在这目的是为了给第二个block进行赋值
            __weak SettingController *BlockSelf = self;
            //回调修改的用户名
            amendVC.block = ^(NSString *string){
                
                BlockSelf.userView.label.text = string;
            };
            //回调修改的用户头像
            amendVC.herderBlcok = ^(UIImageView *imageView){
                NSLog(@"%@",imageView.image);
                BlockSelf.userView.imageView.image = imageView.image;
            };
        }
        
        //消息视图的轻拍手势
        else if ([tapLabel.text isEqualToString:@"消息中心"]){
            
            MessageCenterController *messageVC = [[MessageCenterController alloc]init];
            messageVC.messageArray = [NSMutableArray array];
            messageVC.messageArray = self.messageArray;
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"message"];
            
            [self.navigationController pushViewController:messageVC animated:YES];
            
            
        }
        
//        //近期阅读的轻拍手势
//        else if ([tapLabel.text isEqualToString:@"近期阅读"]){
//            
//            RecentlyReadController *recentlyVC = [[RecentlyReadController alloc]init];
//            
//            [self.navigationController pushViewController:recentlyVC animated:YES];
//        }
//        
//        //离线阅读的轻拍手势
//        else if ([tapLabel.text isEqualToString:@"离线阅读"]){
//            
//            Off_LineReadController *offlineVC = [[Off_LineReadController alloc]init];
//            
//            [self.navigationController pushViewController:offlineVC animated:YES];
//        }
        
        //设置按钮的轻拍手势
        else if ([tapLabel.text isEqualToString:@"设置"]){
            ExitController *exitVC = [[ExitController alloc]init];
            
            [self.navigationController pushViewController:exitVC animated:YES];
            
            //当登陆界面 成功后 程序才会执行这个block的代码快 就是进行回调
            //在这目的是为了给第二个block进行赋值
            __weak SettingController *BlockSelf = self;
            
            exitVC.block = ^(NSString *string){
                
                BlockSelf.userView.label.text = string;
               
            };
            
            exitVC.herderBlock = ^(UIImageView *imageView){
                 BlockSelf.userView.imageView.image = imageView.image;
            };

        }
        
//        //设置按钮的轻拍手势
//        else if ([tapLabel.text isEqualToString:@"夜间模式"]){
//            
//            tapLabel.text = @"日间模式";
//            
//            UIImageView *imageView = tap.view.subviews[0];
//            
//            //设置新图片
//            imageView.image = [UIImage imageNamed:@"sun.png"];
//            
//        }
//        
//        //设置按钮的轻拍手势
//        else if ([tapLabel.text isEqualToString:@"日间模式"]){
//            
//            tapLabel.text = @"夜间模式";
//            
//            UIImageView *imageView = tap.view.subviews[0];
//            
//            //设置新图片
//            imageView.image = [UIImage imageNamed:@"night.png"];
//            
//        }
    }
    
    //没有登陆
    else{
        
        //是用户界面 或者是用户的主页 的轻拍手势
        if ([tapLabel.text isEqualToString:self.userView.label.text] || [tapLabel.text isEqualToString:@"我的主页"]) {
            //要先判断是否登陆 没登陆进入登陆界面
            LoginController *loginVC = [[LoginController alloc]init];
            
            [self.navigationController pushViewController:loginVC animated:YES];
            
            //当登陆界面 成功后 程序才会执行这个block的代码快 就是进行回调
            //在这目的是为了给第二个block进行赋值
            __weak SettingController *BlockSelf = self;
            
            loginVC.block = ^(NSString *string,UIImageView *imageView){
                
                BlockSelf.userView.label.text = string;
                NSLog(@"%@",imageView.image);
                BlockSelf.userView.imageView.image = imageView.image;
            };

        }
        
//        //设置按钮的轻拍手势
//        else if ([tapLabel.text isEqualToString:@"夜间模式"]){
//            
//            tapLabel.text = @"日间模式";
//            
//            UIImageView *imageView = tap.view.subviews[0];
//            
//            //设置新图片
//            imageView.image = [UIImage imageNamed:@"sun.png"];
//            
//        }
//
//        //设置按钮的轻拍手势
//        else if ([tapLabel.text isEqualToString:@"日间模式"]){
//            
//            tapLabel.text = @"夜间模式";
//            
//            UIImageView *imageView = tap.view.subviews[0];
//            
//            //设置新图片
//            imageView.image = [UIImage imageNamed:@"night.png"];
//            
//        }
        //提示:显示请先登陆
        else{
            
            [self alertActionWithTitle:@"提示" message:@"请先登陆" other:@"确定"];
        
        }
    
    }
    
    
    
    

    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
